<template>
  <el-dialog v-if="load" title="授权" v-model="visible" append-to-body width="500px" @close="handleClose">
    <el-form ref="formRef" :model="form" label-position="top">
      <el-form-item label="开发者账号" prop="ad_id" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
        <div class="flex items-center w-full">
          <VSelect v-model="form.ad_id" placeholder="请选择" :options="form.developer" class="w-full" />
          <div v-if="adInfo.tip === '已授权'" class="whitespace-nowrap ml-2 text-green-600">{{adInfo.tip}}</div>
          <div v-else class="whitespace-nowrap ml-2 text-red-600">{{adInfo.tip}}</div>
        </div>
      </el-form-item>
      <el-form-item label="授权区域" prop="auth_area" class="col-span-3">
        <VSelect v-model="form.auth_area" placeholder="请选择" :disabled="form.shop_id && form.sp_api_status === 1" :options="options.auth_area" class="w-full"
          @change="({ option }) => form.auth_area_tip = option.tip" />
      </el-form-item>
      <div>{{ form.auth_area_tip }}</div>
      <div class="text-red-600 leading-4 mt-2">点击登录亚马逊授权将跳转到亚马逊卖家后台，请在常用环境操作，避免关联</div>
    </el-form>
    <template #footer>
      <el-button @click="close">关 闭</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">{{ form.shop_id && form.sp_api_status === 1? '更新授权' : '授权' }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from './api'
import { ElMessage } from 'element-plus'
import { getOption } from '@/api/public'
import { handleLink } from './utils'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})
const form = ref({})
const formRef = ref()

const emit = defineEmits(['close', 'success'])

const adInfo = computed(() => form.value.developer.find(d => d.value === form.value.ad_id) || {})

// 打开弹窗
const open = async (params) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  loadings = reactive({})
  visible.value = true
  form.value = params
  form.value.ad_id = params.developer[0].value
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}

// 提交
const submit = async () => {
  if (!await formRef?.value.validate()) return
  loadings.submit = true
  handleLink(form.value)
  loadings.submit = false
}

defineExpose({ open })
</script>